#!/bin/bash
# 进入脚本所在目录
cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" || exit


blue()  { echo  "\033[34m$1\033[0m"; }
red()   { echo  "\033[31m$1\033[0m"; }

# 检查 Milvus 相关容器是否已启动
check_container() {
    local container_name=$1
    local image_name=$2
    local state=$(docker ps -a --filter name="$container_name" --format "table {{.State}}" |grep -v "STATE" 2>/dev/null)
    if [[ "$state" != "running" ]]; then
        red "容器 $container_name ($image_name) 未启动"
        # 如果是 paused 状态, 则先unpause ,以便于后续启动 docker compose up -d
        if [[ "$state" == "paused" ]]; then  
            docker unpause "$container_name" 2>/dev/null 1>&2
        fi
        return 1
    else
        echo "容器 $container_name ($image_name) 已启动"
        return 0
    fi
}

# 检查并启动Docker
echo "检查并启动Docker daemon..."
sh  ./start_docker_daemon.sh
if [ $? -ne 0 ]; then
    echo "Docker daemon启动失败，退出脚本"
    exit 1
fi
blue "Docker daemon 启动成功"

echo ""
echo "检查Milvus服务容器是否已启动..."
# 检查三个必要的容器
milvus_standalone_status=0
milvus_etcd_status=0
milvus_minio_status=0

check_container "milvus-standalone" "milvusdb/milvus:v2.5.4"
milvus_standalone_status=$?

check_container "milvus-etcd" "coreos/etcd:v3.5.16"
milvus_etcd_status=$?

check_container "milvus-minio" "minio/minio:RELEASE.2023-03-20T20-16-18Z"
milvus_minio_status=$?

# 如果任何一个容器未启动，则启动所有服务
if [ $milvus_standalone_status -ne 0 ] || [ $milvus_etcd_status -ne 0 ] || [ $milvus_minio_status -ne 0 ]; then
    blue "Milvus 服务容器未完全启动，开始启动 ..."
    docker compose up -d
    if [ $? -ne 0 ]; then
        echo "启动 Milvus 服务失败"
        exit 1
    fi
    
    # 等待 Milvus 容器完全启动
    echo ""
    echo "等待 Milvus 容器完全启动 ..."
    max_wait=30  # 最大等待时间（秒）
    wait_interval=2  # 检查间隔（秒）
    elapsed_time=0
    
    # 定义等待函数
    wait_for_containers() {
        while [ $elapsed_time -lt $max_wait ]; do
            # 重新检查所有容器状态
            check_container "milvus-standalone" "milvusdb/milvus:v2.5.4"
            local sa_status=$?
            
            check_container "milvus-etcd" "coreos/etcd:v3.5.16"
            local etcd_status=$?
            
            check_container "milvus-minio" "minio/minio:RELEASE.2023-03-20T20-16-18Z"
            local minio_status=$?
            
            # 如果所有容器都已启动，返回成功
            if [ $sa_status -eq 0 ] && [ $etcd_status -eq 0 ] && [ $minio_status -eq 0 ]; then
                return 0
            fi
            
            # 等待指定间隔
            sleep $wait_interval
            elapsed_time=$((elapsed_time + wait_interval))
            echo "已等待 $elapsed_time 秒，继续等待容器启动..."
        done
        
        # 超时，返回失败
        return 1
    }
    
    # 执行等待函数
    if ! wait_for_containers; then
        echo "等待 Milvus 容器启动超时（${max_wait}秒）"
        exit 1
    fi    
fi

echo ""
echo "Milvus服务容器状态 (名称、状态和端口)..."
docker compose ps -a --format "table {{.Name}}\t{{.State}}\t{{.Ports}}"
blue "Milvus 服务容器已全部启动成功"
echo ""
